//
//  TongxunluViewController.m
//  Fengshui
//
//  Created by are on 13-5-28.
//
//

#import "TongxunluViewController.h"
#import "POAPinyin.h"
@interface TongxunluViewController ()

@end

@implementation TongxunluViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (BOOL)checkTel:(NSString *)str
{
    NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //    Dlog(@"phoneTest is %@",phoneTest);
    return [phoneTest evaluateWithObject:str];
}
-(void)loadContacts
{
    for (int i = 0; i < 26; i++) [self.sectionDic setObject:[NSMutableArray array] forKey:[NSString stringWithFormat:@"%c",'A'+i]];
    [self.sectionDic setObject:[NSMutableArray array] forKey:[NSString stringWithFormat:@"%c",'#']];
    ABAddressBookRef myAddressBook  = nil;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0)
    {
        myAddressBook = ABAddressBookCreateWithOptions(NULL, NULL);
        //等待同意后向下执行
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(myAddressBook, ^(bool granted, CFErrorRef error)
                                                 {
                                                     dispatch_semaphore_signal(sema);
                                                 });
        
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        dispatch_release(sema);
    }
    else
    {
        myAddressBook = ABAddressBookCreate();
    }
    
    CFArrayRef results = ABAddressBookCopyArrayOfAllPeople(myAddressBook);
    CFMutableArrayRef mresults=CFArrayCreateMutableCopy(kCFAllocatorDefault,
                                                        CFArrayGetCount(results),
                                                        results);
    //将结果按照拼音排序，将结果放入mresults数组中
    CFArraySortValues(mresults,
                      CFRangeMake(0, CFArrayGetCount(results)),
                      (CFComparatorFunction) ABPersonComparePeopleByName,
                      (void*) ABPersonGetSortOrdering());
    //遍历所有联系人
    for (int k=0;k<CFArrayGetCount(mresults);k++) {
        ABRecordRef record=CFArrayGetValueAtIndex(mresults,k);
        NSString *personname = (NSString *)ABRecordCopyCompositeName(record);
        ABMultiValueRef phone = ABRecordCopyValue(record, kABPersonPhoneProperty);
        ABRecordID recordID=ABRecordGetRecordID(record);
        if (ABMultiValueGetCount(phone)<1) {

            continue;
            //[self.phoneDic setObject:record forKey:[NSString stringWithFormat:@"无手机号%d",recordID]];
            
        }
        else
        {
//            for (int k = 0; k<ABMultiValueGetCount(phone); k++)
//            {
//
//                
//            NSString * personPhone = (NSString*)ABMultiValueCopyValueAtIndex(phone, k);
//                if ([personPhone length]<3) {
//                    
//                        [self.phoneDic setObject:record forKey:[NSString stringWithFormat:@"%@%d",personPhone,recordID]];
//                    
//                }
//                else
//                {
//                    NSRange range=NSMakeRange(0,3);
//                    NSString *str=[personPhone substringWithRange:range];
//                        if ([str isEqualToString:@"+86"]) {
//                            personPhone=[personPhone substringFromIndex:3];
//                        }
//                    [self.phoneDic setObject:record forKey:[NSString stringWithFormat:@"%@%d",personPhone,recordID]];
//                }
//            }
            
            NSString * personPhone = (NSString*)ABMultiValueCopyValueAtIndex(phone, 0);
            if ([personPhone length]<3) {
               
                continue;
               
                    }
                    else
                    {
                         
                        NSRange range=NSMakeRange(0,3);
                        NSString *str=[personPhone substringWithRange:range];
                                  
                        if ([str isEqualToString:@"+86"]) {
                                    personPhone=[personPhone substringFromIndex:3];
                                        }
                                if ([self checkTel:[personPhone stringByReplacingOccurrencesOfString:@"-" withString:@""]]) {
                                    
                                    [self.phoneDic setObject:record forKey:[NSString stringWithFormat:@"%@%d",personPhone,recordID]];

                                }
            else
            {
                continue;
            }
                    }

        }
        char first=pinyinFirstLetter([personname characterAtIndex:0]);
        NSString *sectionName;
        if ((first>='a'&&first<='z')||(first>='A'&&first<='Z')) {
            if([self searchResult:personname searchText:@"曾"])
                sectionName = @"Z";
            else if([self searchResult:personname searchText:@"解"])
                sectionName = @"X";
            else if([self searchResult:personname searchText:@"仇"])
                sectionName = @"Q";
            else if([self searchResult:personname searchText:@"朴"])
                sectionName = @"P";
            else if([self searchResult:personname searchText:@"查"])
                sectionName = @"Z";
            else if([self searchResult:personname searchText:@"能"])
                sectionName = @"N";
            else if([self searchResult:personname searchText:@"乐"])
                sectionName = @"Y";
            else if([self searchResult:personname searchText:@"单"])
                sectionName = @"S";
            else
                sectionName = [[NSString stringWithFormat:@"%c",pinyinFirstLetter([personname characterAtIndex:0])] uppercaseString];
        }
        else {
            sectionName=[[NSString stringWithFormat:@"%c",'#'] uppercaseString];
        }

        [[self.sectionDic objectForKey:sectionName] addObject:record];
        [self.contactDic setObject:record forKey:[NSNumber numberWithInt:recordID]];
        
    }
    

}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (![self.searchDisplayController isActive]) {
        [self loadContacts];
        [self.tableView reloadData];
    }
    [self.searchDisplayController.searchResultsTableView reloadData];

}
- (void)viewDidLoad
{
    [super viewDidLoad];
   
    self.sectionDic = [NSMutableDictionary dictionary];
    self.phoneDic = [NSMutableDictionary dictionary];
    self.filteredArray = [NSMutableArray array];
    self.contactDic = [NSMutableDictionary dictionary];
        [self loadContacts];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)btnActionForPipei:(NSInteger)cellIndex
{
    
}
#pragma mark - Table view data source

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if ([tableView isEqual:self.tableView]) {
        NSMutableArray *indices = [NSMutableArray arrayWithObject:UITableViewIndexSearch];
        for (int i = 0; i < 27; i++)
            [indices addObject:[[ALPHA substringFromIndex:i] substringToIndex:1]];
        //[indices addObject:@"\ue057"]; // <-- using emoji
        return indices;
    }
    return nil;
}
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    if (title == UITableViewIndexSearch)
	{
		[self.tableView scrollRectToVisible:self.searchDisplayController.searchBar.frame animated:NO];
		return -1;
	}

    return  [ALPHA rangeOfString:title].location;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([tableView isEqual:self.tableView]) {
        return 27;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:self.tableView]) {
        NSString *key=[NSString stringWithFormat:@"%c",[ALPHA characterAtIndex:section]];
        return  [[self.sectionDic objectForKey:key] count];
    }
    return [self.filteredArray count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]) {
        return nil;
    }
    NSString *key=[NSString stringWithFormat:@"%c",[ALPHA characterAtIndex:section]];
    if ([[self.sectionDic objectForKey:key] count]!=0) {
        
        return key;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80.0f;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    TongxueluCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (![tableView isEqual:self.tableView]) {
        //搜索结果
        if (cell == nil) {
            
            cell = [[[NSBundle mainBundle] loadNibNamed:@"TongxueluCell" owner:self options:nil] objectAtIndex:0];
        }
         NSDictionary *person=[self.filteredArray objectAtIndex:indexPath.row];
         cell.nameLabel.text=[person objectForKey:@"name"];
        if ([person objectForKey:@"image"]) {
            
            cell.perSonalImageView.image = [UIImage imageWithData:[person objectForKey:@"image"]];
            
        }
        else
        {
            cell.perSonalImageView.image = [UIImage imageNamed:@"tongxunludefault.jpg"];
        }

        cell.cellPhoneLabel.text = [person objectForKey:@"phone"];
                 //cell.detailTextLabel.text=[person objectForKey:@"phone"];
         
    }
    else {
        
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"TongxueluCell" owner:self options:nil] objectAtIndex:0];
        }
        NSString *key=[NSString stringWithFormat:@"%c",[ALPHA characterAtIndex:indexPath.section]];
        NSMutableArray *persons=[self.sectionDic objectForKey:key];
        ABRecordRef record=[persons objectAtIndex:indexPath.row];
        
        cell.nameLabel.text = (NSString *)ABRecordCopyCompositeName(record);
        NSData *imageData=(NSData*)ABPersonCopyImageData(record);
        if (imageData) {
            
            cell.perSonalImageView.image = [UIImage imageWithData:imageData];
        }
        else
        {
            cell.perSonalImageView.image = [UIImage imageNamed:@"tongxunludefault.jpg"];
        }
          ABMultiValueRef phone = ABRecordCopyValue(record, kABPersonPhoneProperty);
        if (ABMultiValueGetCount(phone)>0) {

            NSString *string = [NSString string];
            string = [string stringByAppendingString:(NSString*)ABMultiValueCopyValueAtIndex(phone, 0)];
            cell.cellPhoneLabel.text = string;
            
        } 
        
        
        //        NSData *imageData=(NSData*)ABPersonCopyImageData(record);
        //
        //        [cell.imageView setImage:[UIImage imageWithData:imageData]];
        //         cell.imageView.contentMode=UIViewContentModeScaleToFill;
    }
    cell.delegate = self;
    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
     if (![tableView isEqual:self.tableView])
     {
         PipeViewController *viewController = [[PipeViewController alloc] initWithNibName:@"PipeViewController" bundle:nil];
         viewController.record = [[self.filteredArray objectAtIndex:indexPath.row] objectForKey:@"theOne"];
         [self.parentViewController.navigationController pushViewController:viewController animated:YES];
         
     }
      else
     {
         PipeViewController *viewController = [[PipeViewController alloc] initWithNibName:@"PipeViewController" bundle:nil];
         NSString *key=[NSString stringWithFormat:@"%c",[ALPHA characterAtIndex:indexPath.section]];
         NSMutableArray *persons=[self.sectionDic objectForKey:key];
         viewController.record = [persons objectAtIndex:indexPath.row];
         [self.parentViewController.navigationController pushViewController:viewController animated:YES];

     }
}
#pragma UISearchDisplayDelegate
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self performSelectorOnMainThread:@selector(searchWithString:) withObject:searchString waitUntilDone:YES];
    
    return YES;
}
-(void)searchWithString:(NSString *)searchString
{
    [self.filteredArray removeAllObjects];
    NSString * regex        = @"(^[0-9]+$)";
    NSPredicate * pred      = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if ([searchString length]!=0) {
        if ([pred evaluateWithObject:searchString]) { //判断是否是数字
            NSArray *phones=[self.phoneDic allKeys];
            for (NSString *phone in phones) {
                if ([self searchResult:phone searchText:searchString]) {
                    ABRecordRef person=[self.phoneDic objectForKey:phone];
                    ABRecordID recordID=ABRecordGetRecordID(person);
                    NSString *ff=[NSString stringWithFormat:@"%d",recordID];
                    
                    NSString *name=(NSString *)ABRecordCopyCompositeName(person);
              
                    NSMutableDictionary *record=[[NSMutableDictionary alloc] init];
                    if (name) {
                        
                        [record setObject:name forKey:@"name"];
                    }
                    
                    [record setObject:[phone substringToIndex:(phone.length-ff.length)] forKey:@"phone"];
                    [record setObject:[NSNumber numberWithInt:recordID] forKey:@"ID"];
                    NSData *imageData = (NSData *)ABPersonCopyImageData(person);
                    if (imageData) {

                        [record setObject:imageData forKey:@"image"];
                    }
                    [record setObject:person forKey:@"theOne"];
                    [self.filteredArray addObject:record];
                    [record release];
                   
                }
            }
        }
        else {
            //搜索对应分类下的数组
            NSString *sectionName = [[NSString stringWithFormat:@"%c",pinyinFirstLetter([searchString characterAtIndex:0])] uppercaseString];
            NSArray *array=[self.sectionDic objectForKey:sectionName];
            for (int j=0;j<[array count];j++) {
                ABRecordRef person=[array objectAtIndex:j];
                NSString *name=(NSString *)ABRecordCopyCompositeName(person);
                if ([self searchResult:name searchText:searchString]) { //先按输入的内容搜索
                    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
                    NSString * personPhone = (NSString*)ABMultiValueCopyValueAtIndex(phone, 0);
                    ABRecordID recordID=ABRecordGetRecordID(person);
                    NSMutableDictionary *record=[[NSMutableDictionary alloc] init];
                    if (name) {

                        [record setObject:name forKey:@"name"];
                    }
                    if (personPhone) {
                        
                        [record setObject:personPhone forKey:@"phone"];
                    }

                    NSData *imageData = (NSData *)ABPersonCopyImageData(person);
                    if (imageData) {

                        [record setObject:imageData forKey:@"image"];
                    }
                    [record setObject:[NSNumber numberWithInt:recordID] forKey:@"ID"];
                    [record setObject:person forKey:@"theOne"];
                    [self.filteredArray addObject:record];
                    [record release];
                }
                else { //按拼音搜索
                    NSString *string = @"";
                    NSString *firststring=@"";
                    for (int i = 0; i < [name length]; i++)
                    {
                        if([string length] < 1)
                            string = [NSString stringWithFormat:@"%@",
                                      [POAPinyin quickConvert:[name substringWithRange:NSMakeRange(i,1)]]];
                        else
                            string = [NSString stringWithFormat:@"%@%@",string,
                                      [POAPinyin quickConvert:[name substringWithRange:NSMakeRange(i,1)]]];
                        if([firststring length] < 1)
                            firststring = [NSString stringWithFormat:@"%c",
                                           pinyinFirstLetter([name characterAtIndex:i])];
                        else
                        {
                            if ([name characterAtIndex:i]!=' ') {
                                firststring = [NSString stringWithFormat:@"%@%c",firststring,
                                               pinyinFirstLetter([name characterAtIndex:i])];
                            }

                        }
                    }
                    if ([self searchResult:string searchText:searchString]
                        ||[self searchResult:firststring searchText:searchString])
                    {
                        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
                        NSString * personPhone = (NSString*)ABMultiValueCopyValueAtIndex(phone, 0);
                        ABRecordID recordID=ABRecordGetRecordID(person);
                        NSMutableDictionary *record=[[NSMutableDictionary alloc] init];
                        [record setObject:name forKey:@"name"];
                        [record setObject:personPhone forKey:@"phone"];
                        NSData *imageData = (NSData *)ABPersonCopyImageData(person);
                        if (imageData) {

                            [record setObject:imageData forKey:@"image"];

                        }
                        [record setObject:[NSNumber numberWithInt:recordID] forKey:@"ID"];
                        [record setObject:person forKey:@"theOne"];
                        [self.filteredArray addObject:record];
                        [record release];

                    }
                }
            }
        }
    }
}
-(void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller
{
    
}
-(BOOL)searchResult:(NSString *)contactName searchText:(NSString *)searchT{
	NSComparisonResult result = [contactName compare:searchT options:NSCaseInsensitiveSearch
											   range:NSMakeRange(0, searchT.length)];
	if (result == NSOrderedSame)
		return YES;
	else
		return NO;
}
@end
